import React from "react";
import type { DataAction, IProTableRef } from "@yaf/pro-ui";
import { RespDataType, getDeptList } from "../../api";

export const getDataAction = (_: React.MutableRefObject<IProTableRef>, setIsShow: (val: boolean) => void): DataAction => ({
  fetchList: (params) => {
    const { filter } = params;
    return getDeptList(Object.assign({ "deptName": "", "status": "" }, filter || {})).then((resp) => {
      const treeData = toTree(resp.data.deptList);
      setIsShow(true)
      return treeData
    })
  },
})

/**
 * 将数据转为树状数据结构
 */
const toTree = (dataList: RespDataType.DeptTreeItem[]) => {
  const parentId = Math.min(...dataList.map(item => item.parentId));
  const loop = (parentId: number): RespDataType.DeptTree => {
    const res: RespDataType.DeptTree = []
    for (let i = 0; i < dataList.length; i++) {
      const item = dataList[i]

      if (item.parentId !== parentId) {
        continue
      }

      item.children = loop(item.deptId)
      res.push(item)
    }
    return res.length > 0 ? res : null
  }

  return loop(parentId)
}


